package com.techq.lib.socket;


import java.io.*;
import java.net.*;

/**
 * 
 * @author tassemble@gmail.com
 * 待测试 beta版
 */
class SocketClient {

	

	public void main(String[] args) {
		String host = "localhost";
		int port = 10000;
		startClient(host, port);
	}

	private void startClient(String host, int port) {
		BufferedReader br = null;
		PrintWriter pw = null;
		Socket s = null;
		try {
			s = connectServer(host, port);

			br = createReader(s);

			pw = createWriter(br, s);

			writeMsg(pw, "DATA");

			readMsg(br);

			writeMsg(pw, "PAUSE");

			writeMsg(pw, "DOW");

			readMsg(br);

			// Send the DOM command to the server.

			writeMsg(pw, "DOM");

			// Obtain and print the current day of month.

			readMsg(br);

			// Send the DOY command to the server.

			writeMsg(pw, "DOY");

			// Obtain and print the current day of year.

			readMsg(br);
		} catch (IOException e) {
			System.out.println(e.toString());
		} finally {
			try {
				if (br != null)
					br.close();

				if (pw != null)
					pw.close();

				if (s != null)
					s.close();
			} catch (IOException e) {
				System.out.println(e.toString());
			}
		}
	}

	private String readMsg(BufferedReader br) throws IOException {
		// Obtain and print the current date/time.

		return br.readLine();
	}

	private void writeMsg(PrintWriter pw, String msg) {
		// Send the DATE command to the server.
		pw.println(msg);
	}

	private PrintWriter createWriter(BufferedReader br, Socket s)
			throws IOException {
		PrintWriter pw;
		// Create a print writer that chains to the socket's byte-
		// oriented output stream. The print writer creates an
		// intermediate output stream writer that converts
		// characters sent to the socket to bytes. The conversion
		// is based on the platform's default character set.

		pw = new PrintWriter(s.getOutputStream(), true);

		return pw;
	}

	private BufferedReader createReader(Socket s) throws IOException {

		// Create an input stream reader that chains to the socket's
		// byte-oriented input stream. The input stream reader
		// converts bytes read from the socket to characters. The
		// conversion is based on the platform's default character
		// set.

		InputStreamReader isr = new InputStreamReader(s.getInputStream());

		// Create a buffered reader that chains to the input stream
		// reader. The buffered reader supplies a convenient method
		// for reading entire lines of text.

		BufferedReader br = new BufferedReader(isr);
		return br;
	}

	private Socket connectServer(String host, int port) throws UnknownHostException,
			IOException {
		// Create a socket that attempts to connect to the server
		// program on the host at port 10000.

		Socket s = new Socket(host, port);
		return s;
	}
}
